package com.zqh.myfmmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-01-21 22:22
 */
@Component
public class CheckTokenInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求
        String method = request.getMethod();
        if ("options".equalsIgnoreCase(method)) {
            return true;
        }
        String token = request.getHeader("token");
        Result result = null;
        if (token == null) {
            result = Result.againLogin("请先登录");
            doResponse(response,result);
            return false;
        }else{
            int verify = JwtUtil.verify(token);
            if (verify == -1 || verify == -3) {
                result = Result.againLogin("登录已过期，请重新登录");
                doResponse(response,result);
                return false;
            }
            if(verify == -2){
                result = Result.fail("token不合法");
                doResponse(response,result);
                return false;
            }

        }
        //以上异常情况都无则放行
        return true;
    }

    /**
     * 功能描述:
     *  被拦截验证不通过将对应结果写入返回体
     * @param
     * @return
     * @author kono曾淇杭哒！
     * @date 2022/1/26 23:01
     */
    private void doResponse (HttpServletResponse response,Result result)throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(result);
        out.write(s);
        out.flush();
        out.close();
    }
}
